package com.bl.weilan.service.biz.starinfo.impl;

import com.bl.weilan.common.utils.UUIDUtils;
import com.bl.weilan.dao.model.StarInfoEntity;
import com.bl.weilan.dao.model.TrainEntity;
import com.bl.weilan.dao.repository.StarInfoRepository;
import com.bl.weilan.dao.repository.TrainRepository;
import com.bl.weilan.service.biz.starinfo.StarInfoService;
import com.bl.weilan.service.vo.starinfo.StarInfoListVo;
import com.bl.weilan.service.vo.train.TrainListVo;
import com.bl.weilan.service.vo.train.TrainVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Log4j2
public class StarInfoServiceImpl implements StarInfoService {
    @Autowired
    StarInfoRepository starInfoRepository;

    @Autowired
    TrainRepository trainRepository;

    @Override
    public TrainListVo getList(String userId){
        List<StarInfoEntity> starInfoEntities = new ArrayList<>();
        starInfoEntities = starInfoRepository.findByUserId(userId);

        TrainListVo trainListVo = new TrainListVo();
        List<TrainVo> trainVos = new ArrayList<>();
        for (StarInfoEntity starInfoEntity : starInfoEntities) {
            TrainEntity trainEntity = trainRepository.findOne(starInfoEntity.getTrainId());
            TrainVo trainVo = new TrainVo();
            BeanUtils.copyProperties(trainEntity, trainVo);
            trainVo.setUpdateTime(starInfoEntity.getCreateTime());
            trainVos.add(trainVo);
        }
        trainListVo.setTotalCount(starInfoEntities.size());
        trainListVo.setList(trainVos);
        return trainListVo;
    }


    @Override
    public void mod( String userId, String trainId) {
        StarInfoEntity starInfoEntity = new StarInfoEntity();
        starInfoEntity = starInfoRepository.findByTrainIdAndUserId(trainId, userId);
        if(starInfoEntity == null) { //添加收藏
            starInfoEntity = new StarInfoEntity();
            starInfoEntity.setId(UUIDUtils.getUUID());
            starInfoEntity.setCreateTime(new Date());
            starInfoEntity.setUserId(userId);
            starInfoEntity.setTrainId(trainId);

            TrainEntity trainEntity = new TrainEntity();
            trainEntity = trainRepository.findOne(trainId);
            String title = "";
            if(trainEntity != null) {
                title = trainEntity.getTitle();
            }
            starInfoEntity.setTitle(title);

            starInfoRepository.save(starInfoEntity);

        } else { //取消收藏
            String id = starInfoEntity.getId();
            starInfoRepository.delete(id);
        }
    }
}
